//
//  Flyweight.swift
//  AQDeal
//
//  Created by zhangjikuan on 2020/5/29.
//  Copyright © 2020 hsgd. All rights reserved.
//

import Foundation
/// 享元设计模式

class UnsharedConcreteFlyweight {
    var info: String?

    public init(info: String) {
        self.info = info
    }
}
class Flyweight: NSObject {
    public func operation(state: UnsharedConcreteFlyweight) {
        
    }
}

class ConcreteFlyweight: Flyweight {
    var key: String?
    
    public init(key: String) {
        self.key = key
        print("具体享元"+key+"被创！")

    }
    
    override func operation(state: UnsharedConcreteFlyweight) {
        print("具体享元"+"\(String(describing: key))"+"被创建！")
        print("非享元信息是:"+"\(String(state.info!))")
    }
    
    
    
}
class FlyweightFactory
{
//    private HashMap<String, Flyweight> flyweights=new HashMap<String, Flyweight>();
//    public Flyweight getFlyweight(String key)
//    {
//        Flyweight flyweight=(Flyweight)flyweights.get(key);
//        if(flyweight!=null)
//        {
//            System.out.println("具体享元"+key+"已经存在，被成功获取！");
//        }
//        else
//        {
//            flyweight=new ConcreteFlyweight(key);
//            flyweights.put(key, flyweight);
//        }
//        return flyweight;
//    }
    
    private var flyweights = [String: Flyweight]()
    
    public func getFlyweight(key: String) -> Flyweight {
        var flyWeight = self.flyweights[key]
        if (flyWeight != nil) {
            print("具体享元"+"\(key)"+"已经存在，被成功获取！")
        } else {
            flyWeight = ConcreteFlyweight.init(key: key)
            flyweights[key] = flyWeight
        }
        
        return flyWeight!
    }
}
